#include <py32f0xx_hal.h>
#include <py32f002b_ll_i2c.h>

#include "main.h"
#include <i2c_slave.h>
#include <usart.h>
#include "adc.h"

static struct I2CSlaveDummyRegister g_I2CSlaveDummyRegister[4] = {
    {
        .addr = 0x00, //浓度
        .data = {0x00, 0x00, 0x00, 0x00},
        .isUpdate = 0,
        .isReadOnly = 1,
    },
    {
        .addr = 0x11, //版本号
        .data = {0x00, 0x00, 0x00, 0x01},
        .isUpdate = 0,
        .isReadOnly = 1,
    },
    {
        .addr = 0x20, //电阻
        .data = {0x00, 0x00, 0x00, 0x00},
        .isUpdate = 0,
        .isReadOnly = 1,
    },
    {
        .addr = 0x01, //零点校准
        .data = {0x00, 0x00, 0x00, 0x00},
        .isUpdate = 0,
        .isReadOnly = 0,
    },
};

int main(void) {
    HAL_Init();

    //初始化串口打印
    struct UsartInitParam usart1InitParam = {};
    usart1InitParam.gpioPin = GPIO_PIN_3 | GPIO_PIN_4;
    usart1InitParam.gpioPort = GPIOA;
    usart1InitParam.BaudRate = 115200;
    USART1_Init(&usart1InitParam);

    //初始化i2c1 slave
    struct I2CSlaveInitParam i2c1InitParam = {};
    i2c1InitParam.address = 0x34;
    i2c1InitParam.freq = 100*1000; //i2c freq 100k
    i2c1InitParam.gpioPin = GPIO_PIN_3 | GPIO_PIN_4;
    i2c1InitParam.gpioPort = GPIOB;
    I2C1_SlaveInit(&i2c1InitParam, g_I2CSlaveDummyRegister, 4);

    //初始化 adc1
    struct ADCInitParam adc1InitParam = {};
    adc1InitParam.gpioPin = GPIO_PIN_6;
    adc1InitParam.gpioPort = GPIOA;
    ADC1_Init(&adc1InitParam);

    printf("start---------------\r\n");

    while (1) {
        uint16_t adcValue = ADC1_getValueByChannel(ADC_CHANNEL_3);
        //1.原始ADC值转换为电阻,更新到g_I2CSlaveDummyRegister[2]中
        //依据实际电路加入转换算法,将ADC值转换为电阻值
        //demo将ADC值直接更新到g_I2CSlaveDummyRegister[2]中
        g_I2CSlaveDummyRegister[0].data[0] = (uint8_t)(adcValue >> 8); //need fix
        g_I2CSlaveDummyRegister[0].data[1] = (uint8_t)(adcValue & 0x00FF);

        //2.原始ADC值转换为浓度,更新到g_I2CSlaveDummyRegister[0]中
        //依据实际电路加入转换算法,将ADC值转换为浓度值
        //demo将ADC值直接更新到g_I2CSlaveDummyRegister[0]中
        g_I2CSlaveDummyRegister[2].data[0] = (uint8_t)(adcValue >> 8); //need fix
        g_I2CSlaveDummyRegister[2].data[1] = (uint8_t)(adcValue & 0x00FF);

        if ( g_I2CSlaveDummyRegister[3].isUpdate == 1 ) { //用户更新了零点校准数据
            //保存零点校准数据
            for ( int32_t i = 0; i < MAX_REG_DATA_SIZE; i++ ) {
                printf("data:0x%02x \r\n", g_I2CSlaveDummyRegister[3].data[i]);
            }
            g_I2CSlaveDummyRegister[3].isUpdate = 0;
        }

        printf("adcValue:0x%04x \r\n", adcValue);
        HAL_Delay(1000);
    }
}

